import java.util.*;

/**
 * @Description 查找字符串出现的次数
 * @Author hhy
 * @Date 2020/9/29 11:11
 */
public class SearchStringNumber {

       static HashSet<Integer> set = new HashSet<>();
       static List<Integer> list = new ArrayList<>();

    public static void main(String[] args) {
        String str = "ababababababccccabab";

        solution2(str,"ab");
        System.out.println(list.size());


    }

    //一开始想到的，使用穷举，但是时间复杂度更高
    public static void solution(String str,String target){
        for (int i = 0; i < str.length(); i++) {
            int num = str.indexOf(target,i);
            if (num!=-1){
                set.add(num);
            }
        }
    }

    //优化了效率
    public static void solution2(String str,String target){
       int firstNum = str.indexOf(target);
       if (firstNum==-1) return;
       int lastNum = str.lastIndexOf(target);
       list.add(firstNum);
       while (firstNum!=lastNum){
           firstNum = str.indexOf(target,firstNum+1);
           list.add(firstNum);
       }
    }
}
